package com.example.mydy;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ProgressBar;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.mydy.adapter.RewardManagementAdapter;
import com.example.mydy.model.RewardTask;
import com.example.mydy.utils.NetworkUtils;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class RewardManagementActivity extends AppCompatActivity implements RewardManagementAdapter.OnRewardManagementListener {
    private static final String TAG = "RewardManagementActivity";
    
    private Toolbar toolbar;
    private SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView recyclerView;
    private ProgressBar progressBar;
    private TextView tvNoRewards;
    private FloatingActionButton fabAddReward;
    private List<RewardTask> rewardTasks = new ArrayList<>();
    private List<RewardTask> filteredRewardTasks = new ArrayList<>();
    private RewardManagementAdapter adapter;
    
    // 统计数据显示
    private TextView tvTotalTasks;
    private TextView tvPendingReview;
    private TextView tvCompletionRate;
    
    // 筛选标签
    private TextView tagAll;
    private TextView tagInProgress;
    private TextView tagUnderReview;
    private TextView tagCompleted;
    private TextView tagRejected;
    
    // 当前选中的标签
    private int currentStatusFilter = -1; // -1表示全部
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reward_management);
        
        initViews();
        setupRecyclerView();
        setupFilterTags();
        loadRewards();
    }
    
    private void initViews() {
        toolbar = findViewById(R.id.toolbar_reward_management);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayShowTitleEnabled(false);
        }
        
        // 返回按钮
        findViewById(R.id.btn_back).setOnClickListener(v -> finish());
        
        swipeRefreshLayout = findViewById(R.id.swipe_refresh_layout);
        recyclerView = findViewById(R.id.rv_rewards);
        progressBar = findViewById(R.id.progress_bar);
        tvNoRewards = findViewById(R.id.tv_no_rewards);
        fabAddReward = findViewById(R.id.fab_add_reward);
        
        // 统计视图
        tvTotalTasks = findViewById(R.id.tv_total_tasks);
        tvPendingReview = findViewById(R.id.tv_pending_review);
        tvCompletionRate = findViewById(R.id.tv_completion_rate);
        
        // 筛选标签
        tagAll = findViewById(R.id.tag_all);
        tagInProgress = findViewById(R.id.tag_in_progress);
        tagUnderReview = findViewById(R.id.tag_under_review);
        tagCompleted = findViewById(R.id.tag_completed);
        tagRejected = findViewById(R.id.tag_rejected);
        
        swipeRefreshLayout.setOnRefreshListener(this::loadRewards);
        fabAddReward.setOnClickListener(v -> showAddRewardDialog());
        
        // 刷新按钮
        findViewById(R.id.btn_refresh).setOnClickListener(v -> {
            Toast.makeText(this, "正在刷新悬赏列表...", Toast.LENGTH_SHORT).show();
            loadRewards();
        });
    }
    
    private void setupFilterTags() {
        // 设置筛选标签点击事件
        tagAll.setOnClickListener(v -> {
            updateTagSelection(tagAll, -1);
        });
        
        tagInProgress.setOnClickListener(v -> {
            updateTagSelection(tagInProgress, RewardTask.STATUS_IN_PROGRESS);
        });
        
        tagUnderReview.setOnClickListener(v -> {
            updateTagSelection(tagUnderReview, RewardTask.STATUS_UNDER_REVIEW);
        });
        
        tagCompleted.setOnClickListener(v -> {
            updateTagSelection(tagCompleted, RewardTask.STATUS_COMPLETED);
        });
        
        tagRejected.setOnClickListener(v -> {
            updateTagSelection(tagRejected, RewardTask.STATUS_REJECTED);
        });
    }
    
    private void updateTagSelection(TextView selectedTag, int statusFilter) {
        // 重置所有标签样式
        tagAll.setBackgroundResource(R.drawable.bg_tag_normal);
        tagAll.setTextColor(getResources().getColor(android.R.color.darker_gray));
        
        tagInProgress.setBackgroundResource(R.drawable.bg_tag_normal);
        tagInProgress.setTextColor(getResources().getColor(android.R.color.darker_gray));
        
        tagUnderReview.setBackgroundResource(R.drawable.bg_tag_normal);
        tagUnderReview.setTextColor(getResources().getColor(android.R.color.darker_gray));
        
        tagCompleted.setBackgroundResource(R.drawable.bg_tag_normal);
        tagCompleted.setTextColor(getResources().getColor(android.R.color.darker_gray));
        
        tagRejected.setBackgroundResource(R.drawable.bg_tag_normal);
        tagRejected.setTextColor(getResources().getColor(android.R.color.darker_gray));
        
        // 设置选中标签样式
        selectedTag.setBackgroundResource(R.drawable.bg_tag_selected);
        selectedTag.setTextColor(getResources().getColor(android.R.color.white));
        
        // 更新筛选条件
        currentStatusFilter = statusFilter;
        
        // 更新列表
        filterTasks();
    }
    
    private void filterTasks() {
        filteredRewardTasks.clear();
        
        if (currentStatusFilter == -1) {
            // 显示全部任务
            filteredRewardTasks.addAll(rewardTasks);
        } else {
            // 根据状态筛选
            for (RewardTask task : rewardTasks) {
                if (task.getProgressStatus() == currentStatusFilter) {
                    filteredRewardTasks.add(task);
                }
            }
        }
        
        // 更新适配器
        adapter.updateData(filteredRewardTasks);
        
        // 显示或隐藏无数据提示
        if (filteredRewardTasks.isEmpty()) {
            tvNoRewards.setVisibility(View.VISIBLE);
        } else {
            tvNoRewards.setVisibility(View.GONE);
        }
    }
    
    private void setupRecyclerView() {
        adapter = new RewardManagementAdapter(this, filteredRewardTasks, this);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);
    }
    
    private void loadRewards() {
        progressBar.setVisibility(View.VISIBLE);
        
        String token = NetworkUtils.getAuthToken(this);
        if (token == null || token.isEmpty()) {
            Toast.makeText(this, "未登录，请先登录", Toast.LENGTH_SHORT).show();
            loadFallbackData();
            return;
        }
        
        UserApi api = NetworkUtils.getAuthenticatedUserApi(this);
        Call<RewardListResponse> call = api.getRewards("Bearer " + token);
        call.enqueue(new Callback<RewardListResponse>() {
            @Override
            public void onResponse(Call<RewardListResponse> call, Response<RewardListResponse> response) {
                progressBar.setVisibility(View.GONE);
                
                if (response.isSuccessful() && response.body() != null) {
                    RewardListResponse rewardResponse = response.body();
                    if (rewardResponse.isSuccess()) {
                        rewardTasks.clear();
                        rewardTasks.addAll(rewardResponse.getRewards());
                        adapter.notifyDataSetChanged();
                        updateStatistics();
                        filterTasks();
                    } else {
                        Toast.makeText(RewardManagementActivity.this, 
                                       "加载失败: " + rewardResponse.getMessage(), 
                                       Toast.LENGTH_SHORT).show();
                        loadFallbackData();
                    }
                } else {
                    Toast.makeText(RewardManagementActivity.this, 
                                   "加载失败: " + response.code(), 
                                   Toast.LENGTH_SHORT).show();
                    loadFallbackData();
                }
            }
            
            @Override
            public void onFailure(Call<RewardListResponse> call, Throwable t) {
                progressBar.setVisibility(View.GONE);
                Toast.makeText(RewardManagementActivity.this, 
                               "网络错误: " + t.getMessage(), 
                               Toast.LENGTH_SHORT).show();
                loadFallbackData();
            }
        });
    }
    
    private void loadFallbackData() {
        // 清空奖励任务列表
        rewardTasks.clear();
        adapter.notifyDataSetChanged();
        
        // 显示错误提示
        tvNoRewards.setVisibility(View.VISIBLE);
        tvNoRewards.setText("无法加载悬赏任务数据");
        
        // 向用户提示错误
        Toast.makeText(this, "无法从服务器加载悬赏任务数据，请检查网络连接", Toast.LENGTH_LONG).show();
        Log.e(TAG, "无法从服务器加载悬赏任务数据");
        
        // 更新界面状态
        progressBar.setVisibility(View.GONE);
        updateStatistics();
        filterTasks();
    }
    
    private void updateStatistics() {
        if (rewardTasks == null || rewardTasks.isEmpty()) {
            tvTotalTasks.setText("0");
            tvPendingReview.setText("0");
            tvCompletionRate.setText("0%");
            return;
        }
        
        // 总任务数
        int totalTasks = rewardTasks.size();
        tvTotalTasks.setText(String.valueOf(totalTasks));
        
        // 待审核任务数
        int pendingReview = 0;
        for (RewardTask task : rewardTasks) {
            if (task.getProgressStatus() == RewardTask.STATUS_UNDER_REVIEW) {
                pendingReview++;
            }
        }
        tvPendingReview.setText(String.valueOf(pendingReview));
        
        // 完成率
        int completedTasks = 0;
        for (RewardTask task : rewardTasks) {
            if (task.getProgressStatus() == RewardTask.STATUS_COMPLETED) {
                completedTasks++;
            }
        }
        int completionRate = (totalTasks > 0) ? (completedTasks * 100 / totalTasks) : 0;
        tvCompletionRate.setText(completionRate + "%");
    }
    
    private void showAddRewardDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_edit_reward_task, null);
        
        // 找到对话框标题
        TextView tvDialogTitle = dialogView.findViewById(android.R.id.title);
        if (tvDialogTitle == null) {
            // 如果没有使用标准Android ID，查找第一个TextView
            tvDialogTitle = dialogView.findViewWithTag("dialog_title");
            if (tvDialogTitle == null) {
                // 作为备选方案，使用布局中的第一个TextView
                if (dialogView instanceof ViewGroup) {
                    ViewGroup viewGroup = (ViewGroup) dialogView;
                    for (int i = 0; i < viewGroup.getChildCount(); i++) {
                        View child = viewGroup.getChildAt(i);
                        if (child instanceof TextView) {
                            tvDialogTitle = (TextView) child;
                            break;
                        }
                    }
                }
            }
        }
        
        if (tvDialogTitle != null) {
            tvDialogTitle.setText("添加新悬赏");
        }
        
        EditText etTitle = dialogView.findViewById(R.id.et_edit_title);
        EditText etDescription = dialogView.findViewById(R.id.et_edit_description);
        EditText etReward = dialogView.findViewById(R.id.et_edit_reward);
        EditText etDeadline = dialogView.findViewById(R.id.et_edit_deadline);
        EditText etRemainingOrders = dialogView.findViewById(R.id.et_edit_remaining_orders);
        Button btnSave = dialogView.findViewById(R.id.btn_save);
        
        // 更改按钮文字
        if (btnSave != null) {
            btnSave.setText("发布悬赏");
        }
        
        // 构建对话框
        AlertDialog dialog = builder.setView(dialogView).create();
        
        // 设置发布按钮点击事件
        if (btnSave != null) {
            btnSave.setOnClickListener(v -> {
                String title = etTitle.getText().toString().trim();
                String description = etDescription.getText().toString().trim();
                String rewardStr = etReward.getText().toString().trim();
                String deadline = etDeadline.getText().toString().trim();
                String remainingOrdersStr = etRemainingOrders.getText().toString().trim();
                
                if (TextUtils.isEmpty(title) || TextUtils.isEmpty(description) || 
                    TextUtils.isEmpty(rewardStr) || TextUtils.isEmpty(deadline) || 
                    TextUtils.isEmpty(remainingOrdersStr)) {
                    Toast.makeText(this, "请填写所有必填字段", Toast.LENGTH_SHORT).show();
                    return;
                }
                
                double reward;
                int remainingOrders;
                
                try {
                    reward = Double.parseDouble(rewardStr);
                } catch (NumberFormatException e) {
                    Toast.makeText(this, "悬赏金额必须是数字", Toast.LENGTH_SHORT).show();
                    return;
                }
                
                try {
                    remainingOrders = Integer.parseInt(remainingOrdersStr);
                } catch (NumberFormatException e) {
                    Toast.makeText(this, "可接名额必须是整数", Toast.LENGTH_SHORT).show();
                    return;
                }
                
                // 创建悬赏任务
                RewardTask task = new RewardTask();
                task.setId(generateNewTaskId());
                task.setTitle(title);
                task.setDescription(description);
                task.setReward(reward);
                task.setDeadline(deadline);
                task.setRemainingOrders(remainingOrders);
                task.setEarnedPeople(0);
                task.setCreatedAt(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault()).format(new Date()));
                task.setTaken(false);
                task.setProgressStatus(RewardTask.STATUS_IN_PROGRESS); // 设置为进行中状态
                
                boolean success = NetworkUtils.addRewardTask(task);
                if (success) {
                    Toast.makeText(this, "悬赏发布成功", Toast.LENGTH_SHORT).show();
                    loadRewards();
                    dialog.dismiss();
                } else {
                    Toast.makeText(this, "发布失败，请重试", Toast.LENGTH_SHORT).show();
                }
            });
        }
        
        dialog.show();
    }
    
    // 生成新的任务ID
    private int generateNewTaskId() {
        int maxId = 0;
        for (RewardTask task : rewardTasks) {
            if (task.getId() > maxId) {
                maxId = task.getId();
            }
        }
        return maxId + 1;
    }
    
    private void editTask(RewardTask task) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_edit_reward_task, null);
        
        // 找到对话框标题
        TextView tvDialogTitle = dialogView.findViewById(android.R.id.title);
        if (tvDialogTitle == null) {
            // 如果没有使用标准Android ID，查找第一个TextView
            tvDialogTitle = dialogView.findViewWithTag("dialog_title");
            if (tvDialogTitle == null) {
                // 作为备选方案，使用布局中的第一个TextView
                if (dialogView instanceof ViewGroup) {
                    ViewGroup viewGroup = (ViewGroup) dialogView;
                    for (int i = 0; i < viewGroup.getChildCount(); i++) {
                        View child = viewGroup.getChildAt(i);
                        if (child instanceof TextView) {
                            tvDialogTitle = (TextView) child;
                            break;
                        }
                    }
                }
            }
        }
        
        if (tvDialogTitle != null) {
            tvDialogTitle.setText("编辑悬赏任务");
        }
        
        EditText etEditTitle = dialogView.findViewById(R.id.et_edit_title);
        EditText etEditDescription = dialogView.findViewById(R.id.et_edit_description);
        EditText etEditReward = dialogView.findViewById(R.id.et_edit_reward);
        EditText etEditDeadline = dialogView.findViewById(R.id.et_edit_deadline);
        EditText etEditRemainingOrders = dialogView.findViewById(R.id.et_edit_remaining_orders);
        Button btnSave = dialogView.findViewById(R.id.btn_save);
        
        if (etEditTitle != null) etEditTitle.setText(task.getTitle());
        if (etEditDescription != null) etEditDescription.setText(task.getDescription());
        if (etEditReward != null) etEditReward.setText(String.valueOf(task.getReward()));
        if (etEditDeadline != null) etEditDeadline.setText(task.getDeadline());
        if (etEditRemainingOrders != null) etEditRemainingOrders.setText(String.valueOf(task.getRemainingOrders()));
        
        // 构建对话框
        AlertDialog dialog = builder.setView(dialogView).create();
        
        if (btnSave != null) {
            btnSave.setOnClickListener(v -> {
                String newTitle = etEditTitle.getText().toString().trim();
                String newDesc = etEditDescription.getText().toString().trim();
                String newRewardStr = etEditReward.getText().toString().trim();
                String newDeadline = etEditDeadline.getText().toString().trim();
                String newRemainingStr = etEditRemainingOrders.getText().toString().trim();
                
                if (TextUtils.isEmpty(newTitle) || TextUtils.isEmpty(newDesc) || 
                    TextUtils.isEmpty(newRewardStr) || TextUtils.isEmpty(newDeadline) || 
                    TextUtils.isEmpty(newRemainingStr)) {
                    Toast.makeText(this, "请填写所有必填字段", Toast.LENGTH_SHORT).show();
                    return;
                }
                
                double newReward;
                int newRemaining;
                
                try {
                    newReward = Double.parseDouble(newRewardStr);
                } catch (NumberFormatException e) {
                    Toast.makeText(this, "奖励金额必须是数字", Toast.LENGTH_SHORT).show();
                    return;
                }
                
                try {
                    newRemaining = Integer.parseInt(newRemainingStr);
                } catch (NumberFormatException e) {
                    Toast.makeText(this, "可接名额必须是整数", Toast.LENGTH_SHORT).show();
                    return;
                }
                
                // 更新任务信息
                task.setTitle(newTitle);
                task.setDescription(newDesc);
                task.setReward(newReward);
                task.setDeadline(newDeadline);
                task.setRemainingOrders(newRemaining);
                
                boolean success = NetworkUtils.updateRewardTask(task);
                if (success) {
                    Toast.makeText(this, "任务更新成功", Toast.LENGTH_SHORT).show();
                    loadRewards();
                    dialog.dismiss();
                } else {
                    Toast.makeText(this, "更新失败，请重试", Toast.LENGTH_SHORT).show();
                }
            });
        }
        
        dialog.show();
    }
    
    private void deleteTask(RewardTask task) {
        new AlertDialog.Builder(this)
            .setTitle("删除任务")
            .setMessage("确定要删除这个悬赏任务吗？")
            .setPositiveButton("确定", (dialog, which) -> {
                boolean success = NetworkUtils.deleteRewardTask(task.getId());
                if (success) {
                    Toast.makeText(this, "任务删除成功", Toast.LENGTH_SHORT).show();
                    loadRewards();
                } else {
                    Toast.makeText(this, "删除失败，请重试", Toast.LENGTH_SHORT).show();
                }
            })
            .setNegativeButton("取消", null)
            .show();
    }
    
    // 显示任务详情对话框
    private void showRewardDetailDialog(RewardTask task) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_reward_detail, null);
        
        // 设置任务信息
        TextView tvTitle = dialogView.findViewById(R.id.tv_reward_title);
        TextView tvAmount = dialogView.findViewById(R.id.tv_reward_amount);
        TextView tvDeadline = dialogView.findViewById(R.id.tv_reward_deadline);
        TextView tvRemainingOrders = dialogView.findViewById(R.id.tv_remaining_orders);
        TextView tvStatus = dialogView.findViewById(R.id.tv_reward_status);
        TextView tvDescription = dialogView.findViewById(R.id.tv_reward_description);
        
        // 设置任务详情
        tvTitle.setText(task.getTitle());
        tvAmount.setText(String.format(Locale.CHINA, "¥ %.2f", task.getReward()));
        tvDeadline.setText(task.getDeadline());
        tvRemainingOrders.setText(String.valueOf(task.getRemainingOrders()));
        tvStatus.setText(task.getProgressStatusText());
        tvDescription.setText(task.getDescription());
        
        // 设置任务申请记录
        TextView tvNoApplications = dialogView.findViewById(R.id.tv_no_applications);
        TextView tvApplicationsCount = dialogView.findViewById(R.id.tv_applications_count);
        LinearLayout layoutApplications = dialogView.findViewById(R.id.layout_applications);
        
        // 提交内容区域
        ViewGroup cardApplications = dialogView.findViewById(R.id.card_applications);
        if (task.getSubmissionContent() != null && !task.getSubmissionContent().isEmpty()) {
            tvNoApplications.setVisibility(View.GONE);
            layoutApplications.setVisibility(View.VISIBLE);
            tvApplicationsCount.setVisibility(View.VISIBLE);
            
            // 显示提交内容
            tvApplicationsCount.setText("用户提交内容:");
            
            // 创建提交内容视图
            View submissionView = LayoutInflater.from(this).inflate(R.layout.item_submission, null);
            TextView tvSubmissionContent = submissionView.findViewById(R.id.tv_submission_content);
            TextView tvSubmissionTime = submissionView.findViewById(R.id.tv_submission_time);
            
            tvSubmissionContent.setText(task.getSubmissionContent());
            tvSubmissionTime.setText("提交时间: " + formatDate(task.getSubmissionTime()));
            
            layoutApplications.addView(submissionView);
        } else {
            // 没有提交内容
            tvNoApplications.setVisibility(View.VISIBLE);
            layoutApplications.setVisibility(View.GONE);
            tvApplicationsCount.setVisibility(View.GONE);
        }
        
        // 如果当前不是待审核状态，隐藏审核部分
        ViewGroup cardReviewSection = dialogView.findViewById(R.id.card_review_section);
        if (task.getProgressStatus() != RewardTask.STATUS_UNDER_REVIEW) {
            cardReviewSection.setVisibility(View.GONE);
        } else {
            // 如果是待审核状态，设置审核按钮事件
            Button btnReject = dialogView.findViewById(R.id.btn_reject);
            Button btnApprove = dialogView.findViewById(R.id.btn_approve);
            EditText etReviewComment = dialogView.findViewById(R.id.et_review_comment);
            
            btnReject.setOnClickListener(v -> {
                String comment = etReviewComment.getText().toString().trim();
                // 更新任务状态为已拒绝
                updateTaskStatus(task, RewardTask.STATUS_REJECTED, comment);
                builder.create().dismiss();
            });
            
            btnApprove.setOnClickListener(v -> {
                String comment = etReviewComment.getText().toString().trim();
                // 更新任务状态为已完成
                updateTaskStatus(task, RewardTask.STATUS_COMPLETED, comment);
                builder.create().dismiss();
            });
        }
        
        // 设置关闭按钮
        Button btnClose = dialogView.findViewById(R.id.btn_close);
        btnClose.setOnClickListener(v -> builder.create().dismiss());
        
        // 显示对话框
        builder.setView(dialogView).create().show();
    }
    
    // 格式化日期
    private String formatDate(String dateString) {
        if (dateString == null || dateString.isEmpty()) {
            return "未知时间";
        }
        
        try {
            if (dateString.contains("T")) {
                SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault());
                SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
                return outputFormat.format(inputFormat.parse(dateString));
            }
            return dateString;
        } catch (Exception e) {
            return dateString;
        }
    }
    
    /**
     * 更新任务状态
     */
    private void updateTaskStatus(RewardTask task, int newStatus, String comment) {
        task.setProgressStatus(newStatus);
        task.setReviewComment(comment);
        task.setReviewTime(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault()).format(new Date()));
        task.setContext(this); // 设置上下文以便在NetworkUtils中使用
        
        boolean success = NetworkUtils.updateRewardTask(task);
        if (success) {
            String statusText = (newStatus == RewardTask.STATUS_COMPLETED) ? "通过" : "拒绝";
            Toast.makeText(this, "任务已" + statusText, Toast.LENGTH_SHORT).show();
            loadRewards();
        } else {
            Toast.makeText(this, "操作失败，请重试", Toast.LENGTH_SHORT).show();
        }
    }
    
    // OnRewardManagementListener接口实现
    @Override
    public void onViewDetail(RewardTask task) {
        showRewardDetailDialog(task);
    }

    @Override
    public void onEdit(RewardTask task) {
        editTask(task);
    }

    @Override
    public void onDelete(RewardTask task) {
        deleteTask(task);
    }

    @Override
    public void onReview(RewardTask task) {
        showRewardDetailDialog(task);
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        // 每次恢复活动时重新加载数据
        loadRewards();
    }
}